package com.tanhua.server.serivce;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.ContactVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MessagesService {

    @DubboReference
    private FriendApi friendApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    /**
     * 添加联系人
     *   userId:对方的用户id
     */
    public void contacts(Long userId) {
        Long currUserId = UserHolder.getUserId();
        //1、保存好友关系到mongodb
        friendApi.save(userId,currUserId);
        //2、将好友关系注册到环信
        huanXinTemplate.addContact("hx"+userId,"hx"+currUserId);//环信用户
    }

    //分页查询好友列表
    public PageResult findFriends(Integer page, Integer pagesize) {
        //1、获取用户id
        Long userId = UserHolder.getUserId();
        //2、调用API分页查询好友列表  List<Friend>
        List<Friend> list = friendApi.findByUserId(userId,page,pagesize);
        //3、如果好友数据不存在，返回
        if(CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        List<Long> userIds = CollUtil.getFieldValues(list, "friendId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds);
        //4、List<Friend>集合构建一个List<ContactVo>
        List<ContactVo> vos = new ArrayList<>();
        for (Friend friend : list) {
            //ContactVo : 好友的用户信息
            UserInfo userInfo = map.get(friend.getFriendId());
            ContactVo vo = ContactVo.init(userInfo);
            vos.add(vo);
        }
        //5、构建返回值  0i
        return new PageResult(page,pagesize,0l,vos);
    }

    //根据环信id查询，用户信息
    //环信id = hx + id
    public UserInfoVo findByhuanxinId(String huanxinId) {
        //1、删除hx，获取用户id
        String str = huanxinId.substring(2);
        Long userId = Long.valueOf(str);
        //2、调用API查询用户信息
        UserInfo userInfo = userInfoApi.findById(userId);
        //3、构造vo
        UserInfoVo vo = new UserInfoVo();
        //工具类转化
        BeanUtils.copyProperties(userInfo,vo); //将UserInfo中同名，同类型的属性，自动赋值到vo中
        //不同的，单独处理
        if(userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }
        return vo;
    }
}
